<?php

include_once APPLICATION_DIR . "/application/model/CATEGORY.php";

class Category extends DataObjects_CATEGORY
{
	function getList($filter = array(), &$pager=false)
	{
		$category = new Category();
		if (isset($filter['name']) && $filter['name']) {
			$category->whereAdd(DRX_StringUtils::getI18nRealValueSql('CATEGORY.NAME')." LIKE '%".mysql_escape_string($filter['name'])."%'");
		}
        $category->joinAdd(new Menu());
		$category->whereAdd("CATEGORY.IS_DELETED = ".IS_NOT_DELETED);
        $category->selectAdd();
        $category->selectAdd("CATEGORY.*, MENU.NAME MENU");
		$category->orderBy("CATEGORY.POSITION ASC, ".DRX_StringUtils::getI18nRealValueSql("CATEGORY.NAME"));
		if ($pager == true) {
			$pager = new DBPager($category, $filter, true);
		}
		
		$category->find();

		return $category;
	}

	public function isExistsByName($id = 0, $name= '', $lang_code = '')
	{
		if ($name == '')
		{
			return false;
		}	
		$category = new Category();
		if ($id) {
			$category->whereAdd("ID <> {$id}");
		}
        if ($lang_code) {
            $slq = " NAME LIKE '%<{$lang_code}>".trim($name)."</{$lang_code}>%'";
        } else {
            $slq = DRX_StringUtils::isI18nSqlCheckStringUnique($name, 'NAME');
        }
		$category->whereAdd($slq);
        $category->find();
		return $category->N > 0;
	}
    
    public function isExistsByIds($ids = 0)
	{
		if (!is_array($ids))
		{
			return false;
		}	
		$category = new Category();
		$category->whereAdd("ID IN (".  implode(",", $ids).")");
        $category->whereAdd("IS_DELETED = 0");
        $category->find();
		return $category->N == count($ids)?true:false;
	}

	public function validateInput($name_arr){
		global $error_msg;

        if (!count($name_arr)) {
            $error_msg->add(_MSG_INVALID_CATEGORY_NAME);
        } else {
            if (!isset($name_arr[REQ_LANG])) {
                $message = _LB_CATEGORY_NAME._MSG_VALUE_NAME_BY_LANGUAE_MISSING;
                $message = str_replace("[LANGUAGE]", "&lt;en&gt;", $message);
                $error_msg->add($message);
            }
            
            $name = "";
            foreach($name_arr as $code => $value) {
                $message = _MSG_VALUE_NAME_BY_LANGUAE_INVALID;
                $message = str_replace("[LANGUAGE]", "&lt;$code&gt;", $message);
                if (!textvalid($value))
                {
                    $error_msg->add($message);
                }

                if (self::isExistsByName($this->ID, $value, $code))
                {
                    $message = _MSG_VALUE_NAME_BY_LANGUAGE_EXISTS;
                    $message = str_replace("[LANGUAGE]", "&lt;$code&gt;", $message);
                    $error_msg->add($message);
                }

                $name .= "<".$code.">".$value."</".$code.">";
            }

            $this->NAME = $name;
        }
        
        if (!textvalid($this->POSITION)) {
			$error_msg->add(_MSG_POSITION_NOT_EMPTY);
		}
		
		if (!is_numeric($this->POSITION) || (intval($this->POSITION) != $this->POSITION) || ($this->POSITION < 0)) {
			$error_msg->add(_MSG_POSITION_INVALID);
		}
                
        if (self::isExistsByPosition($this->POSITION, $this->ID))
		{
			$error_msg->add(_MSG_EMPLACEMENT_POSITION_EXISTS);
		}
        
        if (!textvalid($this->ID_MENU)) {
            $error_msg->add(_MSG_MENU_NOT_EMPTY);
        } else {
            $menu = new Menu();
            if (!$menu->get($this->ID_MENU)) {
                $error_msg->add(_MSG_MENU_INVALID);
            }
        }
		return $error_msg->isNoError();
	}

    function isExistsByPosition($position= 0, $id = 0)
	{
		$category = new Category();
		if ($id) {
			$category->whereAdd("ID <> {$id}");
		}

		$category->POSITION = $position;
        $category->IS_DELETED = 0;
        $category->find();
		
		return $category->N > 0;
	}
    
	function deleteLogic()
	{
		if (!$this->IS_DELETED && self::isDeleteAble($this->ID)) {
			$this->NAME = DRX_StringUtils::appendIdtoName($this->ID, $this->NAME);
			$this->IS_DELETED = IS_DELETED;
			$this->STATUS = STATUS_TO_SYNCHRONIZE;
			$this->update();
		}
	}

	/**
	* Get extension of an image file, based on the mime type
	*
	* @param string $filename
	* @return string
	*/
	function getImageType($filename)
	{
		$image_info = getimagesize($filename);
		$type = $image_info['mime'];

		switch($type)
		{
		   case 'image/pjpeg':
		   case 'image/jpeg':
		   case 'image/jpg':
		 		return '.jpg';
		 		break;
		   case 'image/png':
		   case 'image/x-png':
		   		return '.png';
		   		break;
		   case 'image/gif':
		   		return '.gif';
		   		break;
//		   case 'image/bmp':
//		   		return '.bmp';
//		   		break;
		   default:
		   		return '';
		   		break;
		}
	}
	
	public function isDeleteAble($id = 0) {
        $category_video_provider = new Category_Video_Provider();
        $category_video_provider->ID_CATEGORY = $id;
        $category_video_provider->find();
        return $category_video_provider->N > 0?false:true;	        
	}
	
	function getCategories($categories) {
        $cat_arr = array();
        $category_names = "";
        if ($categories) {
            $category_arr = explode(",", $categories);
            foreach ($category_arr as $category) {
                if ($category) {
                    $cat_arr[] = $category;
                }
            }
        }
        if ($cat_arr) {
            $categories = implode (",", $cat_arr); 
            $category = new Category();
            $category->whereAdd("ID IN ({$categories})");
            $category->whereAdd("IS_DELETED = 0");
            $category->orderBy(DRX_StringUtils::getI18nRealValueSql("NAME"));
            $category->find();
            while($category->fetch()) {
                if ($category_names) {
                    $category_names = $category_names.", ".DRX_StringUtils::getI18n($category->NAME);
                } else {
                    $category_names = DRX_StringUtils::getI18n($category->NAME);
                }
            }
        }
		return $category_names;
	}
}
